<template>
	<el-dialog v-model="dialogFormVisible" width="450px" destroy-on-close class="login-css">
		<el-page-header @back="goBack">
			<template #content>
				<span class="text-large font-800 mr-3">登录网易云</span>
			</template>
		</el-page-header>
		<div class="login-container">
			<el-form ref="userRef" :model="user" class="login-form" label-width="10px">
				<el-form-item prop="user_name">
					<el-input v-model="user.user_name" placeholder="账号(用户名/手机号/邮箱)" clearable @blur="checkUsername()" />
					<el-text class="mx-1" size="small" type="danger">{{userTip.yhmTip}}</el-text>
				</el-form-item>

				<el-form-item prop="user_pwd">
					<el-input v-model="user.user_pwd" type="password" placeholder="密码" clearable @blur="checkPwd()" />
					<el-text class="mx-1" size="small" type="danger">{{userTip.pwdTip}}</el-text>
				</el-form-item>

				<el-form-item prop="captcha">
					<el-col :span="14">
						<el-input v-model="user.captcha" placeholder="请输入验证码" clearable
							@click="checkCaptcha()"></el-input>
						<el-text class="mx-1" size="small" type="danger">{{userTip.captchaTip}}</el-text>
					</el-col>
					<el-col :span="1">
						&nbsp;
					</el-col>
					<el-col :span="9">
						<img :src="yzmUrl" alt="验证码" @click="refreshYzm"
							style="width: 120px; height: 100%; opacity: 0.5;" />
					</el-col>
				</el-form-item>
				<el-button type="primary" style="margin-left:10px;width: 320px;height: 40px;"
					@click="doLogin()">登录</el-button>

				<p>
					<span id="right">
						&nbsp;
						<a href="#" id="left">手机短信登录</a>
						|
						<a href="register">注册</a> |
						<a href="#">忘记密码</a> |
						<a href="ShouYeIndex">首页</a>
					</span>
				</p>

			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="goBack">关闭</el-button>
				<el-button @click="doFormReset">重置</el-button>
				<el-button type="primary" @click="showRegisterPage">注册</el-button>
			</div>
		</template>
	</el-dialog>
	<register-page ref="registerPageRef"></register-page>
</template>
<script lang="ts" setup>
	import { nextTick, onMounted, ref } from 'vue'
	import axios from 'axios';
	import { ElMessage, FormInstance } from 'element-plus'
	import RegisterPage from './RegisterPage.vue'
	const emits = defineEmits(["yincang"]);
	const user = ref({
		user_name: '',
		user_pwd: '',
		captcha: '',
		user_tx: '',
	});
	const userTip = ref({
		yhmTip: '',
		pwdTip: '',
		captchaTip: ''
	})
	const yzmUrl = ref("");
	// "/api/src/directory/output.png"
	const userRef = ref<FormInstance>()
	const goBack = () => {
		window.location.href = "shouYeIndex";
	}

	const registerPageRef = ref();
	const showRegisterPage = () => {
		registerPageRef.value.handleRegisterForm();
	}
	const checkUsername = () => {
		if (user.value.user_name.length == 0 || /^\s+$/.test(user.value.user_name)) {
			userTip.value.yhmTip = '请输入用户名'
			// alert('请输入用户名')
			return false
		} else {
			userTip.value.yhmTip = ''
			return true
		}
	}
	const checkPwd = () => {
		if (/^\d{6,10}$/.test(user.value.user_pwd) == false) {
			userTip.value.pwdTip = '密码非法'
			// alert('密码非法')
			return false
		} else {
			userTip.value.pwdTip = ''
			return true
		}
	}
	//刷新验证码
	const refreshYzm = () => {
		axios.get('/api/user/yzm1').then((response) => {
			console.log(response.data)
			yzmUrl.value = '/api/src/directory/' + response.data;
		});
	}
	//检查验证码
	const checkCaptcha = async () => {
		if (user.value.captcha.length === 0 || /^\s+$/.test(user.value.captcha)) {
			userTip.value.captchaTip = '请输入验证码';
			return false;
		} else {
			try {
				const response = await axios({
					url: '/api/user/yzm1/' + user.value.captcha,
					method: 'get'
				});
				console.log('验证码验证响应：', response);
				if (response.data === true) {
					userTip.value.captchaTip = '';
					return true;
				} else {
					userTip.value.captchaTip = '验证码错误';
					return false;
				}
			} catch (error) {
				console.error('验证码验证错误：', error);
				return false;
			}
		}
	};

	const doLogin = async () => {

		const [usernameValid, passwordValid, captchaValid] = await Promise.all([
			checkUsername(),
			checkPwd(),
			checkCaptcha()
		]);
		if (usernameValid && passwordValid && captchaValid) {
			axios({
				url: '/api/user',
				method: 'GET',
				params: user.value
			}).then((response) => {
				const yh = response.data;



				console.log(response)
				if (null != yh && yh != '') {

					localStorage.setItem("user", JSON.stringify(yh));


					if (yh.user_sf === 2) { // 如果用户类型2，都跳转到管理员页面
						window.location.href = "/admin/musicData";
						emits("yincang");
					} else if (yh.user_sf === 1) { // 如果用户类型为1，跳转到用户页面
						window.location.href = "/pagesIndex/shouYeIndex";
					} else { // 其他情况跳转到首页
						window.location.href = "/pagesIndex/shouYeIndex";
					}
				} else {
					alert("账号有误！");
				}
			});
		}
	}
	const dialogFormVisible = ref(true)



	const handleLoginForm = async () => {
		dialogFormVisible.value = true;
		doFormReset();

		nextTick(() => {
			axios.get('/api/user/yzm1').then((response) => {
				console.log(response.data)
				yzmUrl.value = '/api/src/directory/' + response.data;
			});

		})


	}

	const doFormReset = () => {
		// 重置表单字段 
		if (userRef.value) {
			userRef.value.resetFields();
			userTip.value.yhmTip = '';
			userTip.value.pwdTip = '';
			userTip.value.captchaTip = '';
		}
	};


	// const cancelForm = () => {
	// 	dialogFormVisible.value = false;

	// 	doFormReset();
	// };
	// 将handleAddForm暴露给父组件
	defineExpose({
		handleLoginForm
	})
	// 钩子函数 对验证码初始化
	/* onMounted(() => {
		alert()
		axios.get('/api/user/yzm1').then((response) => {
			console.log(response)
			yzmUrl.value = '/api/src/directory/output.png';
		})
	}) */
</script>
<style>
	.login-container {
		width: 400px;
		height: 350px;
		display: flex;
		justify-content: center;
		align-items: center;
		padding-right: 20px;
		padding-top: 20px;
		margin-top: 20px;
		background-image: url(./adminPage/musicMgr/img.png);
	}

	,
	.login-form {
		width: 400px;
		padding: 20px;
		background-color: #fff;
		border-radius: 5px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, .1);
	}
</style>